/**
 * desc：
 * author：王文军
 * date：  2022/9/10 16:53
 */
"use strict";
const Controller = require("egg").Controller;
const { success, failed } = require("../utils/request");
class UserController extends Controller {
  async createUser() {
    const { ctx, service } = this;
    const { username, password } = ctx.request.body;
    try {
      const userInfo = await service.user.findUser(username);
      if (userInfo.length > 0) {
        ctx.body = failed("该用户已存在，请直接登录！");
      } else {
        const res = await service.user.createUser({ username, password });
        if (res.result.ok) {
          ctx.body = success("用户创建成功");
        } else {
          ctx.body = failed("数据库异常，请稍后重试！");
        }
      }
    } catch (e) {
      console.error(e);
      ctx.body = failed("数据库异常，请稍后重试！");
    }
  }

  async login() {
    const { ctx, service, app } = this;
    const { username, password } = ctx.request.body;
    try {
      const userInfo = (await service.user.findUser(username))[0];
      if (!userInfo) {
        return (ctx.body = failed("该用户不存在，请先注册", "", -2));
      }
      const verifyPwd = await ctx.compare(password, userInfo.password);
      if (!verifyPwd) {
        return (ctx.body = failed("用户名或密码错误"));
      }
      const token = app.jwt.sign(
        { username: userInfo.username, _id: userInfo._id },
        app.config.jwt.secret,
        {
          expiresIn: app.config.jwtExpires,
        }
      );
      ctx.body = success("登录成功！", { token });
    } catch (e) {
      console.error(e);
      ctx.body = failed("数据库异常，请稍后重试！");
    }
  }
}
module.exports = UserController;
